import 'package:efood_multivendor/controller/restaurant_controller.dart';
import 'package:efood_multivendor/data/model/response/restaurant_model.dart';
import 'package:efood_multivendor/helper/size_config.dart';
import 'package:efood_multivendor/util/dimensions.dart';
import 'package:efood_multivendor/util/styles.dart';
import 'package:efood_multivendor/view/base/cart_view.dart';
import 'package:efood_multivendor/view/base/custom_button.dart';
import 'package:efood_multivendor/view/base/product_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_typeahead/flutter_typeahead.dart';
import 'package:get/get.dart';

class ProductSearchResultScreen extends StatefulWidget {
  final Restaurant? restaurant;
  const ProductSearchResultScreen({Key? key, this.restaurant})
      : super(key: key);

  @override
  State<ProductSearchResultScreen> createState() =>
      _ProductSearchResultScreenState();
}

class _ProductSearchResultScreenState extends State<ProductSearchResultScreen> {
  final ScrollController scrollController = ScrollController();
  final TextEditingController _searchController = TextEditingController();
  late final focusNode = FocusNode();
  @override
  void initState() {
    super.initState();
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
              scrollController.position.maxScrollExtent &&
          Get.find<RestaurantController>().searchProductList != null &&
          !Get.find<RestaurantController>().searchProductPaginate &&
          !Get.find<RestaurantController>().isSearchQueryEmpty) {
        int pageSize =
            (Get.find<RestaurantController>().searchProductPageSize / 10)
                .ceil();
        if (Get.find<RestaurantController>().searchProductOffset < pageSize) {
          Get.find<RestaurantController>().setSearchProductOffset(
              Get.find<RestaurantController>().searchProductOffset + 1);
          Get.find<RestaurantController>().showFoodBottomLoader();
          Get.find<RestaurantController>().searchData(
              Get.find<RestaurantController>().searchText,
              widget.restaurant!.id.toString());
        }
      } else if (scrollController.position.pixels ==
              scrollController.position.maxScrollExtent &&
          Get.find<RestaurantController>().restaurantProducts != null) {
        int pageSize =
            (Get.find<RestaurantController>().foodPageSize / 10).ceil();
        if (Get.find<RestaurantController>().foodOffset < pageSize) {
          Get.find<RestaurantController>()
              .setFoodOffset(Get.find<RestaurantController>().foodOffset + 1);
          Get.find<RestaurantController>().showFoodBottomLoader();
          Get.find<RestaurantController>().getRestaurantProductList(
            widget.restaurant!.id!,
            Get.find<RestaurantController>().foodOffset,
            Get.find<RestaurantController>().type,
            false,
          );
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        Get.find<RestaurantController>().toggleSearch();
        return true;
      },
      child: Scaffold(
        body: CartView(
            SafeArea(
                child: Padding(
                    padding: EdgeInsets.symmetric(
                        vertical: Dimensions.PADDING_SIZE_SMALL),
                    child: GetBuilder<RestaurantController>(
                        builder: (restController) {
                      return Column(children: [
                        Center(
                            child: SizedBox(
                                width: Dimensions.WEB_MAX_WIDTH,
                                child: Row(children: [
                                  IconButton(
                                      padding: EdgeInsets.zero,
                                      onPressed: () {
                                        Get.back();
                                      },
                                      icon: Icon(Icons.arrow_back_ios)),
                                  SizedBox(
                                      width:
                                          Dimensions.PADDING_SIZE_EXTRA_SMALL),
                                  Expanded(
                                      child: Hero(
                                    tag: 'search_food_or_restaurant'.tr,
                                    child: Container(
                                      padding: EdgeInsets.all(
                                          Dimensions.PADDING_SIZE_SMALL),
                                      alignment: Alignment.topCenter,
                                      child: Material(
                                        shape: RoundedRectangleBorder(
                                            borderRadius: BorderRadius.circular(
                                                Dimensions.RADIUS_SMALL)),
                                        child: SizedBox(
                                            width: Dimensions.WEB_MAX_WIDTH,
                                            child: TypeAheadField(
                                              textFieldConfiguration:
                                                  TextFieldConfiguration(
                                                focusNode: focusNode,
                                                controller: _searchController,
                                                onSubmitted: (keyword) {
                                                  if (focusNode.hasFocus) {
                                                    focusNode.unfocus();
                                                  }
                                                  restController.searchData(
                                                      keyword,
                                                      widget.restaurant!.id
                                                          .toString());
                                                },
                                                textInputAction:
                                                    TextInputAction.newline,
                                                onEditingComplete: () {
                                                  Get.find<
                                                          RestaurantController>()
                                                      .searchData(
                                                    _searchController.text
                                                        .trim(),
                                                    widget.restaurant!.id
                                                        .toString(),
                                                  );
                                                },
                                                autofocus: true,
                                                textCapitalization:
                                                    TextCapitalization.words,
                                                keyboardType:
                                                    TextInputType.text,
                                                decoration: InputDecoration(
                                                  hintText:
                                                      'search_food_or_restaurant'
                                                          .tr,
                                                  hintStyle: sfRegular.copyWith(
                                                      fontSize: Dimensions
                                                          .fontSizeSmall,
                                                      color: Theme.of(context)
                                                          .disabledColor),
                                                  border: OutlineInputBorder(
                                                      borderRadius: BorderRadius
                                                          .circular(Dimensions
                                                              .RADIUS_SMALL),
                                                      borderSide:
                                                          BorderSide.none),
                                                  filled: true,
                                                  fillColor: Theme.of(context)
                                                      .cardColor,
                                                  isDense: true,
                                                  suffixIcon: IconButton(
                                                    onPressed: () {
                                                      restController.searchData(
                                                          _searchController.text
                                                              .trim(),
                                                          widget.restaurant!.id
                                                              .toString());
                                                      FocusScope.of(context)
                                                          .unfocus();
                                                    },
                                                    icon: Icon(Icons.search),
                                                  ),
                                                ),
                                                style: Theme.of(context)
                                                    .textTheme
                                                    .headlineMedium
                                                    ?.copyWith(
                                                      color: Theme.of(context)
                                                          .textTheme
                                                          .bodyMedium
                                                          ?.color,
                                                      fontSize: Dimensions
                                                          .fontSizeLarge,
                                                    ),
                                              ),
                                              suggestionsCallback:
                                                  (keyword) async {
                                                Future.delayed(
                                                    Duration(milliseconds: 300),
                                                    () {});
                                                final results =
                                                    await restController
                                                        .searchKeyword(
                                                            context,
                                                            keyword,
                                                            'restaurant',
                                                            widget
                                                                .restaurant!.id
                                                                .toString());
                                                return results;
                                              },
                                              getImmediateSuggestions: true,
                                              hideOnError: true,
                                              hideOnEmpty: true,
                                              hideSuggestionsOnKeyboardHide:
                                                  true,
                                              hideOnLoading: true,
                                              autoFlipDirection: true,
                                              itemBuilder:
                                                  (context, String keyword) {
                                                return Padding(
                                                  padding: EdgeInsets.all(
                                                      Dimensions
                                                          .PADDING_SIZE_SMALL),
                                                  child: Row(children: [
                                                    Icon(Icons.food_bank),
                                                    SizedBox(width: 2.w),
                                                    Expanded(
                                                      child: Text(keyword,
                                                          maxLines: 1,
                                                          overflow: TextOverflow
                                                              .ellipsis,
                                                          style: Theme.of(
                                                                  context)
                                                              .textTheme
                                                              .headlineMedium
                                                              ?.copyWith(
                                                                color: Theme.of(
                                                                        context)
                                                                    .textTheme
                                                                    .bodyMedium
                                                                    ?.color,
                                                                fontSize: Dimensions
                                                                    .fontSizeLarge,
                                                              )),
                                                    ),
                                                  ]),
                                                );
                                              },
                                              onSuggestionSelected:
                                                  (String keyword) {
                                                restController.searchData(
                                                    keyword,
                                                    widget.restaurant!.id
                                                        .toString());
                                              },
                                            )),
                                      ),
                                    ),
                                  )),
                                  CustomButton(
                                    onPressed: () {
                                      Get.find<RestaurantController>()
                                          .toggleSearch();
                                    },
                                    buttonText: 'cancel'.tr,
                                    transparent: true,
                                    width: 80,
                                  ),
                                ]))),
                        SizedBox(
                            height: Dimensions.PADDING_SIZE_EXTRA_SMALL * 3),
                        Expanded(
                            child: SingleChildScrollView(
                          child: ProductView(
                            fromRestaurant: true,
                            isRestaurant: false,
                            restaurants: null,
                            products: restController.searchProductList,
                            inRestaurantPage: true,
                            fromRestaurantSearch: true,
                            type: restController.type,
                            onVegFilterTap: (String type) {
                              restController.getRestaurantProductList(
                                  restController.restaurant!.id!,
                                  1,
                                  type,
                                  true);
                            },
                            padding: EdgeInsets.symmetric(
                              horizontal: Dimensions.PADDING_SIZE_SMALL,
                              vertical: 0,
                            ),
                          ),
                        ))
                      ]);
                    }))),
            "",
            restaurantId: widget.restaurant?.id),
      ),
    );
  }
}
